// pages/secretary/secretary.js
import Http from '../../utils/http.js';
import throttle from '../../utils/throttle.js';
import { hasPermission } from '../../utils/tools';
const http = new Http();
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        isIpx: false,
        realName: '',
        address: '',
        phone: '',
        backBoxShow: true,
        swiperImgArr: [],
        swiperImgNum: 0,
        backHeight: '',
        backTop: '',
        ipxBottom: 0,
        // 秘书团
        secretaryArr: [],
        secretaryInfo: false,
        secretaryPersonNum: 0,
        checkinNum: 0,
        checkinPersonNum: 0,
        uidfirst: '', //团长uid
        uidsecond: '', //副团长uid
        // 经验
        // 城市公告
        allCityNotice: false, //展开全部
        cityNoticeid: '',
        cityNoticeList: [], //全部通告
        cityNoticeListitem: [], //通告收起
        cityNoticeLength: 0,
        show: false,
        actions: [
            {
                name: '置顶',
                color: '#333333',
            },
            {
                name: '编辑',
                color: '#333333',
            },
            {
                name: '转移至',
                color: '#333333',
            },
            {
                name: '删除',
                color: '#FF455E',
            },
        ],
        // 操作内容发布人uid
        operateUid: '',
        showNext: false,
        // 写回答
        commentTop: 101,
        commentInfo: false,
        answerDescription: '',
        cityQuestionList: [],
        cityQuestionId: '',
        answerBoxBottom: 0, //回答弹窗键盘高度
        // 操作有问必答
        answerId: '',
        questionId: '',
        answerEdit: false,
        answerEditCont: '', //回答再次编辑内容
        questionrEditCont: '', //问题再次编辑内容
        anonymous: false, //评论匿名
        canCheckIn: false, //打卡两小时限制
        firstparty: '', //服务客户在切换城市后会重置
    },
    checkInTap(e) {
        if (app.globalData.addressBack == app.globalData.addressTap) {
            if (this.data.canCheckIn) {
                wx.navigateTo({
                    url: `../checkIn/checkIn?firstparty=${this.data.firstparty}`,
                });
            } else {
                wx.showToast({
                    title: '两小时内不能重复打卡',
                    icon: 'none',
                    duration: 2000,
                });
            }
        } else {
            wx.showToast({
                title: '距离打卡点较远，目前无法打卡',
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000,
            });
            return;
        }
    },
    photoWallTap(e) {
        wx.navigateTo({
            url: `../photoWall/photoWall?cityname=${app.globalData.addressBack}&cityflg=00&fromWhere=01`,
        });
    },
    //操作记录
    recordTap(e) {
        wx.navigateTo({
            url: `../index/operationRecord/operationRecord?title=${app.globalData.addressBack}·打卡记录&fromWhere=01`,
        });
    },
    //秘书团查看全部
    secretaryTap(e) {
        wx.navigateTo({
            url: `./secretaryInfo/secretaryInfo`,
        });
    },
    // 查看他人主页
    jumpOthersPage(e) {
        wx.navigateTo({
            url: `../../functionPage/pages/othersHomePage/othersHomePage?uid=${e.currentTarget.dataset.uid}`,
        });
    },
    // 发布城市公高
    jumpEditTap(e) {
        wx.navigateTo({
            url: `../../releasePage/pages/addCitytip/addCitytip`,
        });
    },
    //发布问题
    jumpQuestionTap(e) {
        wx.navigateTo({
            url: `../../releasePage/pages/addQuestion/addQuestion`,
        });
    },
    // 有问必答详情
    jumpAnswerInfoTap(e) {
        wx.navigateTo({
            url: `../../functionPage/pages/secretary/questionInfo/questionInfo?id=${e.currentTarget.dataset.id}`,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }
        this.setData({
            realName: app.globalData.realname,
            address: app.globalData.addressBack,
            phone: app.globalData.loginPhone,
            checkNum: options.checkNum,
            isIpx: app.globalData.isIpx,
        });
        this.getCityNoticeList();
        this.getCityQuestionList();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let bubbleInfo = wx.getMenuButtonBoundingClientRect();
        this.setData({
            backHeight: bubbleInfo.height,
            backTop: bubbleInfo.top,
        });
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }
        this.queryCheckIn();
        this.getPhotoWallList();
        this.getHomePageCityInfo();
    },
    onUnload() {
        // 缓存数据
        let _that = this;
        wx.setStorageSync('swiperImg_arr_secretary', _that.data.swiperImgArr);
    },
    refresh() {
        //刷新城市公告
        let _that = this;
        _that.setData({
            cityNoticeList: [],
            cityNoticeListitem: [],
            cityNoticeLength: 0,
            show: false,
            showNext: false,
        });
        _that.getCityNoticeList();
        _that.getCityQuestionList();
    },
    //公告导航
    navigateBtn(e) {
        wx.openLocation({
            //​使用微信内置地图查看位置。
            latitude: e.currentTarget.dataset.lat,
            longitude: e.currentTarget.dataset.lng, //要去的经度-地址
            name: e.currentTarget.dataset.title,
            address: e.currentTarget.dataset.address,
        });
    },
    //单个公告全文展开
    developAllBtn(e) {
        let notice = this.data.cityNoticeList;
        let noticeitem = this.data.cityNoticeListitem;
        if (e.currentTarget.dataset.index > 2) {
            notice[e.currentTarget.dataset.index].describe.developAll = true;
            this.setData({
                cityNoticeList: notice,
            });
        } else {
            notice[e.currentTarget.dataset.index].describe.developAll = true;
            noticeitem[
                e.currentTarget.dataset.index
            ].describe.developAll = true;
            this.setData({
                cityNoticeList: notice,
                cityNoticeListitem: noticeitem,
            });
        }
    },
    // 公告展开收起
    changeCityNotice() {
        this.setData({
            allCityNotice: !this.data.allCityNotice,
        });
    },
    // 获取秘书团照片
    getPhotoWallList(e) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/getPhotoWallList`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
                cityflg: '00', //查城市照片墙填  00
                pageSize: 10,
                pageNo: 1,
                cityname: app.globalData.addressBack, //城市名称
                country: app.globalData.countryBack,
            },
            success: function (res) {
                console.log(res);
                let swiperImg =
                    wx.getStorageSync('swiperImg_arr_secretary') || [];
                let imgArr = [];
                let imgNameArr = [];
                if (res.data.data.length) {
                    for (let i = 0; i < res.data.data.length; i++) {
                        imgArr.push(res.data.data[i].picurl);
                        imgNameArr.push(res.data.data[i].createuname);
                    }
                }
                _that.setData({
                    swiperImgNum: res.data.pager.totalRows,
                });
                if (swiperImg != imgArr) {
                    _that.setData({
                        swiperImgArr: imgArr,
                        swiperImgNameArr: imgNameArr,
                    });
                }
            },
        });
    },
    // 获取秘书团成员
    getHomePageCityInfo() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `code/getHomePageCityInfo`,
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded', // 默认值
            },
            data: {
                country: app.globalData.countryBack,
                city: app.globalData.addressBack,
            },
            success: function (res) {
                console.log(res.data);
                if (
                    !res.data.secretaryList ||
                    res.data.secretaryList.length == 0
                ) {
                    _that.setData({
                        secretaryInfo: false,
                    });
                } else {
                    let first = '';
                    let second = '';
                    if (res.data.secretaryList[0].level) {
                        if (res.data.secretaryList[0].level == '00') {
                            first = res.data.secretaryList[0].uid;
                        }
                        if (res.data.secretaryList[0].level == '01') {
                            second = res.data.secretaryList[0].uid;
                        }
                        if (
                            res.data.secretaryList[1] &&
                            res.data.secretaryList[1].level == '01'
                        ) {
                            second = res.data.secretaryList[1].uid;
                        }
                    }
                    _that.setData({
                        secretaryPersonNum: res.data.secretaryList.length,
                        secretaryArr: res.data.secretaryList.slice(0, 3),
                        secretaryInfo: true,
                        uidfirst: first,
                        uidsecond: second,
                    });
                }
                _that.setData({
                    checkinNum: res.data.checkinNum,
                    checkinPersonNum: res.data.checkinPersonNum,
                });
            },
        });
    },
    // 获取城市公告
    getCityNoticeList(e) {
        let _that = this;
        let data = {
            authId: app.globalData.authId,
            city: app.globalData.addressBack, //城市名称
            country: app.globalData.countryBack,
            pageflg: '01',
        };
        http.getRequest(`code/getCityNoticeList`, data).then((res) => {
            if (res.status == 0) {
                for (let i = 0; i < res.data.length; i++) {
                    res.data[i].picurl = JSON.parse(res.data[i].picurl);
                }
                for (let i = 0; i < res.data.length; i++) {
                    let descValue = {
                        id: '',
                        time: '2019-12-12 13:28',
                        describeText: '',
                        createuid: '',
                        name: '',
                        title: '',
                        address: '',
                        istop: '',
                        lat: '',
                        lng: '',
                    };
                    let arrValue = {
                        describe: {},
                        imageArr: [],
                    };
                    descValue.id = res.data[i].id;
                    descValue.lat = res.data[i].lat;
                    descValue.lng = res.data[i].lng;
                    descValue.developAll = false;
                    descValue.istop = res.data[i].istop;
                    descValue.name = res.data[i].realname;
                    descValue.title = res.data[i].title;
                    descValue.address = res.data[i].address;
                    descValue.time =
                        res.data[i].createtime.slice(0, 4) +
                        '-' +
                        res.data[i].createtime.slice(5, 7) +
                        '-' +
                        res.data[i].createtime.slice(8, 10) +
                        ' ' +
                        res.data[i].createtime.slice(11, 16);
                    descValue.describeText = res.data[i].content;
                    descValue.createuid = res.data[i].createuid;
                    arrValue.describe = descValue;
                    arrValue.imageArr = res.data[i].picurl;
                    if (i < 3) {
                        _that.data.cityNoticeListitem.push(arrValue);
                    }
                    _that.data.cityNoticeList.push(arrValue);
                }
                _that.setData({
                    cityNoticeList: _that.data.cityNoticeList,
                    cityNoticeListitem: _that.data.cityNoticeListitem,
                    cityNoticeLength: res.pager.totalRows,
                });
            }
        });
    },
    // 获取有问必答列表
    getCityQuestionList(e) {
        let _that = this;
        let data = {
            authId: app.globalData.authId,
            city: app.globalData.addressBack, //城市名称
            country: app.globalData.countryBack,
        };
        http.getRequest(`cjMap/getCityQuestionList`, data).then((res) => {
            if (res.status == 0) {
                console.log(res);
                for (let i = 0; i < res.data.length; i++) {
                    for (let j = 0; j < res.data[i].answerlist.length; j++) {
                        res.data[i].answerlist[j].createtime = app.timeago(
                            res.data[i].answerlist[j].createtime
                        );
                    }
                }
                _that.setData({
                    cityQuestionList: res.data,
                });
            }
        });
    },
    // 公告操作
    //显示弹出层
    operate(e) {
        let action = [];
        if (e.currentTarget.dataset.type == '00') {
            action = [
                {
                    name: '编辑',
                    color: '#333333',
                    className: 'notice-edit',
                },
                {
                    name: '删除',
                    color: '#FF455E',
                    className: 'notice-delete',
                },
            ];
            if (hasPermission(['00', '01', '04', '05'])) {
                if (e.currentTarget.dataset.describledetail.istop == '01') {
                    action.splice(
                        0,
                        0,
                        {
                            name: '取消置顶',
                            color: '#333333',
                            className: 'notice-no-choice',
                        },
                        {
                            name: '转移至',
                            color: '#333333',
                            className: 'notice-transfer',
                        }
                    );
                } else {
                    action.splice(
                        0,
                        0,
                        {
                            name: '置顶',
                            color: '#333333',
                            className: 'notice-choice',
                        },
                        {
                            name: '转移至',
                            color: '#333333',
                            className: 'notice-transfer',
                        }
                    );
                }
            }
            this.setData({
                actions: action,
                showNext: false,
                show: true,
                cityNoticeid: e.currentTarget.dataset.describledetail.id,
            });
        } else if (e.currentTarget.dataset.type == '01') {
            action = [
                {
                    name: '编辑',
                    color: '#333333',
                    className: 'question-edit',
                },
                {
                    name: '删除',
                    color: '#FF455E',
                    className: 'question-delete',
                },
            ];
            this.setData({
                actions: action,
                show: true,
                questionId: e.currentTarget.dataset.id,
                questionrEditCont:
                    e.currentTarget.dataset.questioncontent || '',
            });
        } else if ((e.currentTarget.dataset.type = '02')) {
            if (app.powerIdentity('00,01,04,05', e.currentTarget.dataset.uid))
                return; //权限判断
            action = [
                {
                    name: '编辑',
                    color: '#333333',
                    className: 'answer-edit',
                },
                {
                    name: '删除',
                    color: '#FF455E',
                    className: 'answer-delete',
                },
            ];
            this.setData({
                actions: action,
                show: true,
                answerId: e.currentTarget.dataset.id,
                answerEditCont: e.currentTarget.dataset.answercontent || '',
            });
        }
    },
    //取消
    onCancel(e) {
        this.setData({
            show: false,
        });
    },
    onDelect(e) {
        let _that = this;
        _that.setData({
            show: false,
        });
        if (e.detail.className == 'notice-choice') {
            //城市公告置顶
            let data = {
                authId: app.globalData.authId,
                id: _that.data.cityNoticeid,
                istop: '01',
            };
            http.getRequest(`cjMap/setCityNoticeTop`, data).then((res) => {
                if (res.status == 0) {
                    _that.refresh();
                }
            });
        } else if (e.detail.className == 'notice-no-choice') {
            //城市公告取消置顶
            let data = {
                authId: app.globalData.authId,
                id: _that.data.cityNoticeid,
                istop: '00',
            };
            http.getRequest(`cjMap/setCityNoticeTop`, data).then((res) => {
                if (res.status == 0) {
                    _that.refresh();
                }
            });
        } else if (e.detail.className == 'notice-transfer') {
            //城市公告转移
            _that.setData({
                showNext: true,
            });
        } else if (e.detail.className == 'notice-delete') {
            //城市公告删除
            wx.showModal({
                title: '提示：',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        let data = {
                            authId: app.globalData.authId,
                            id: _that.data.cityNoticeid,
                        };
                        http.getRequest(`cjMap/deleteCityNotice`, data).then(
                            (res) => {
                                if (res.status == 0) {
                                    _that.refresh();
                                }
                            }
                        );
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.className == 'notice-edit') {
            wx.navigateTo({
                url: `../../releasePage/pages/addCitytip/addCitytip?id=${_that.data.cityNoticeid}&type=01`,
            });
        } else if (e.detail.className == 'question-edit') {
            wx.navigateTo({
                url: `../../releasePage/pages/addQuestion/addQuestion?id=${_that.data.questionId}&content=${_that.data.questionrEditCont}`,
            });
        } else if (e.detail.className == 'question-delete') {
            wx.showModal({
                title: '提示：',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        wx.request({
                            url:
                                app.globalData.rootPath +
                                `cjMap/deleteCityQuestion?authId=${app.globalData.authId}&id=${_that.data.questionId}`,
                            method: 'POST',
                            header: {
                                'content-type': 'application/json',
                            },
                            success: function (res) {
                                _that.getCityQuestionList();
                                wx.showToast({
                                    title: '删除成功',
                                    icon: 'none',
                                    duration: 1500,
                                });
                            },
                        });
                    }
                },
            });
        } else if (e.detail.className == 'answer-edit') {
            _that.setData({
                answerEdit: true,
                showAnswerBox: true,
                answerDescription: _that.data.answerEditCont,
            });
        } else if (e.detail.className == 'answer-delete') {
            wx.showModal({
                title: '提示：',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        //删除回答
                        wx.request({
                            url:
                                app.globalData.rootPath +
                                `cjMap/deleteCityAnswer?authId=${app.globalData.authId}&id=${_that.data.answerId}`,
                            method: 'POST',
                            header: {
                                'content-type': 'application/json',
                            },
                            success: function (res) {
                                _that.getCityQuestionList();
                            },
                        });
                    }
                },
            });
        }
    },
    // 转移上一步
    upBtn(e) {
        this.setData({
            showNext: false,
            show: true,
        });
    },
    hideTranferCover(e) {
        this.setData({
            showNext: false,
        });
    },
    backHome(e) {
        wx.navigateBack({
            delta: 1,
        });
    },

    onPageScroll: function (e) {
        if (e.scrollTop > 30) {
            this.setData({
                backBoxShow: false,
            });
        } else {
            this.setData({
                backBoxShow: true,
            });
        }
    },
    //打电话
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone,
        });
    },
    //有问必答
    //有问必答锚点
    scrollTopFun(e) {
        if (e.detail.scrollTop > 30) {
            if (this.data.backBoxShow == true) {
                wx.setNavigationBarColor({
                    frontColor: '#000000',
                    backgroundColor: '#ff0000',
                });
            }
            this.setData({
                backBoxShow: false,
            });
        } else {
            if (this.data.backBoxShow == false) {
                wx.setNavigationBarColor({
                    frontColor: '#ffffff',
                    backgroundColor: '#ff0000',
                });
            }
            this.setData({
                backBoxShow: true,
            });
        }
        let query = wx.createSelectorQuery();
        query
            .select('#comment')
            .boundingClientRect((rect) => {
                console.log(rect.top);
                this.setData({
                    commentTop: rect.top,
                });
            })
            .exec();
    },
    // 跳转
    discussBtn() {
        let _that = this;
        if (_that.data.commentTop > 100) {
            _that.setData({
                toView: 'comment',
                commentTop: 0,
            });
        }
    },
    // 写回答弹窗
    showAnswer(e) {
        this.setData({
            showAnswerBox: true,
            cityQuestionId: e.currentTarget.dataset.id,
        });
    },
    //获取键盘高度
    getkeyHeight(e) {
        console.log(e.detail.height);
        this.setData({
            answerBoxBottom: e.detail.height,
        });
    },
    // 切换匿名
    toggle() {
        this.setData({
            anonymous: !this.data.anonymous,
        });
    },
    hideCover(e) {
        this.setData({
            showAnswerBox: false,
        });
    },
    stopEvent(e) {
        return;
    },
    answerDescription(e) {
        this.setData({
            answerDescription: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 500);
    },
    // 提交写回答
    submitAnswer: throttle(
        function (e) {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            if (!_that.data.answerDescription) return;
            if (!_that.data.answerEdit) {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/createCityAnswer?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        content: _that.data.answerDescription,
                        cityquestionid: _that.data.cityQuestionId,
                        anonymousflg: _that.data.anonymous ? '01' : '00',
                    },
                    success: function (res) {
                        if (res.data.status == 0) {
                            _that.setData({
                                showAnswerBox: false,
                                answerDescription: '',
                                anonymous: false, //评论匿名
                            });
                            _that.getCityQuestionList();
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                        } else {
                            wx.showToast({
                                title: '提交失败，请重新录入或联系后台管理',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    },
                });
            } else {
                //编辑回答
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/editCityAnswer?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        content: _that.data.answerDescription,
                        id: _that.data.answerId,
                        anonymousflg: _that.data.anonymous ? '01' : '00',
                    },
                    success: function (res) {
                        if (res.data.status == 0) {
                            _that.setData({
                                showAnswerBox: false,
                                answerDescription: '',
                                answerId: '',
                                answerEdit: false,
                                anonymous: false, //评论匿名
                            });
                            _that.getCityQuestionList();
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                            let pages = getCurrentPages(); //当前页面栈
                            let prevPage = pages[pages.length - 2]; //上一页面
                            prevPage.refresh();
                        } else {
                            wx.showToast({
                                title: '提交失败，请重新录入或联系后台管理',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    },
                });
            }
        },
        2000,
        {
            trailing: false,
        }
    ),

    // 查询能否打卡，是否有两小时限制
    queryCheckIn() {
        http.getRequest(
            `cjMap/auditCheckinTime?authId=${app.globalData.authId}&city=${app.globalData.addressBack}&country=${app.globalData.countryBack}`
        ).then((res) => {
            this.setData({
                canCheckIn: res.checkin === '0',
                firstparty: res.firstparty,
            });
        });
    },
});
